<!--
 * @Author: Wang WeiHao
 * @Date: 2024-09-26 14:42:55
 * @LastEditors: Wang WeiHao
 * @LastEditTime: 2024-10-17 16:50:38
 * @Description: 
 * @FilePath: \geo-base-dm\src\views\main\ai-processing\right_popupShp.vue
-->
<template>
	<div v-show="popupShow" class="ai-popup">
		<!-- sho解译任务提交框 -->
		<popupBox title="统计分析" @close="closePopup" />
		<div class="form-container">
			<el-form ref="formRef" label-position="top" label-width="100px" :model="aiTaskFormData">
				<el-form-item label="统计分析图层:">
					<div>{{ currentTiff }}</div>
				</el-form-item>
				<el-form-item label="分类字段:">
					<el-select v-model="sortField" placeholder="Select" size="small" style="width: 240px">
						<el-option
							v-for="item in classifyOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="数值字段:">
					<el-select v-model="countField" placeholder="Select" size="small" style="width: 240px">
						<el-option
							v-for="item in countTypeOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="统计类型:">
					<el-select v-model="countType" placeholder="Select" size="small" style="width: 240px">
						<el-option
							v-for="item in statisticsOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<!--				<el-form-item label="">-->
				<!--					<el-checkbox v-model="isSarWater">SAR水体</el-checkbox>-->
				<!--				</el-form-item>-->

				<el-form-item label="矢量范围:">
					<el-radio-group v-model="aiTaskFormData.region" @change="changeAreaType">
						<el-radio :label="3">全部范围</el-radio>
						<el-radio :label="6">绘制范围</el-radio>
						<!-- <el-radio :label="9">上传shp范围</el-radio> -->
					</el-radio-group>
				</el-form-item>
				<el-upload
					v-show="aiTaskFormData.region == 9"
					v-model:file-list="uploadFile"
					v-loading="fileLoading"
					class="mb-9"
					drag
					:class="{ noneUpload: uploadFile.length > 0 }"
					action="//"
					:before-upload="beforeFileUpload"
					:on-remove="onRemoveFile"
					accept=".zip"
				>
					<div v-if="uploadFile.length === 0" class="flex flex-col items-center justify-center">
						<div><img src="@img/main/upload-icon.png" alt="" /></div>
						<div>
							<div>上传shp文件</div>
						</div>
					</div>
				</el-upload>
				<div class="bottom-btn-group">
					<el-button class="elBtn" @click="createTask(formRef)"> 开始分析 </el-button>
					<el-button class="failBtn" @click="closePopup"> 取消 </el-button>
				</div>
			</el-form>
		</div>
	</div>
	<el-dialog v-model="resultDialog" title="分析结果" width="850px" append-to-body>
		<div>
			<analysResult :chartsData="chartsData" :listData="[]" />
		</div>
	</el-dialog>
</template>

<script setup lang="ts">
import popupBox from "@cps/popupBox/index.vue";
import { useTaskStore } from "@/store";
import { addTask, shpGeo } from "@/api/ai-processing";
import mapTool from "@/utils/maptools/map";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { queryOptionById, analysByShp, getCountColumn } from "@/api/data-management/index";
import { id } from "element-plus/es/locale";
import analysResult from "./analysResult.vue";
let base_config = BASE_CONFIG;
const formRef = ref<FormInstance>();
const taskStore = useTaskStore();
const popupShow = computed(() => taskStore.shpPopshow);
const currentTiff = computed(() => taskStore.taskInfo?.fileName);
const currentArea = computed(() => taskStore.taskInfo?.geo);
interface Option {
	value: string;
	label: string;
}
onMounted(() => {
	console.log(taskStore.taskInfo);
});
const chartsData = ref([]);
const resultDialog = ref(false);
const sortField = ref("");
const countField = ref("");
const countType = ref("1");
const statisticsOptions = ref([
	{
		value: "1",
		label: "求和",
	},
]);
const countTypeOptions = ref([
	// {
	// 	value: "SHAPE_Area",
	// 	label: "SHAPE_Area",
	// },
]);
const classifyOptions = ref([] as Option[]);
watch(
	() => taskStore.taskInfo?.id,
	(newId: any) => {
		if (newId && taskStore.taskInfo?.type != "1") {
			queryOptionById(newId).then((res) => {
				if (res.code === 200) {
					classifyOptions.value = res.data.map((key: any) => {
						return {
							value: key,
							label: key,
						};
					});
					sortField.value = res.data[0];
					// countField.value = res.data[1];
				}
			});
			getCountColumn(newId).then((res) => {
				if (res.code === 200) {
					countTypeOptions.value = res.data.map((key: any) => {
						return {
							value: key,
							label: key,
						};
					});
					countField.value = res.data[0];
				}
			});
		}
	},
	{ immediate: true } // 立即执行一次，以防初始时 id 已存在
);
// 解译任务创建弹窗 更新1
const aiTaskFormData: {
	type: string[];
	region: number;
	taskName: string;
} = reactive({
	type: [],
	region: 3,
	taskName: "",
});
watch(currentTiff, (newV) => {
	aiTaskFormData.taskName = newV || "";
});

const onTypesChange = (array: any) => {
	if (aiTaskFormData.type[aiTaskFormData.type.length - 1] === "sar_water") {
		aiTaskFormData.type = ["sar_water"];
	} else {
		let index = aiTaskFormData.type.findIndex((t) => t === "sar_water");
		if (index > -1) {
			aiTaskFormData.type.splice(index, 1);
		}
	}
};
const closePopup = () => {
	clearDraw();
	taskStore.setInfo({
		shpPopshow: false,
		taskInfo: null,
	});
};
const isSarWater = ref(false);
// todo 创建解译任务
const createTask = async (formEl: FormInstance | undefined) => {
	console.log(formEl, "formEl");
	if (aiTaskFormData.region == 6 && !currentGeo.value) {
		ElMessage({
			message: "请先选择解译范围",
			type: "error",
		});
		return;
	}
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			// aiTaskFormData.region === 3 ? changeAreaType(3) : "";
			console.log(aiTaskFormData);
			console.log(taskStore.taskInfo);
			// mapTool.
			// 创建解译任务请求参数
			if (taskStore.taskInfo !== null) {
				// if (!currentGeo.value) {

				let taskType = aiTaskFormData.type.length > 1 ? 2 : 0;
				let interpretType;
				if (aiTaskFormData.type.length > 1) {
					interpretType = aiTaskFormData.type.join(",");
				} else {
					interpretType = aiTaskFormData.type[0];
				}
				// 情况三 taskType = 4 ,sar水体解译
				if (isSarWater.value) {
					taskType = 5;
					interpretType = "water";
				}
				let res = await analysByShp(
					taskStore.taskInfo.id,
					countField.value,
					countType.value,
					sortField.value,
					currentGeo.value
				);
				if (res.code === 200) {
					ElMessage({
						message: "分析成功",
						type: "success",
					});
					chartsData.value = res.data;
					resultDialog.value = true;

					// 修改store状态，更新左侧list
					// taskStore.setInfo({
					// 	taskStatus: false,
					// 	taskInfo: null,
					// });
					// 如果当前还处于绘制状态，移除绘制交互
					if (currentFeature) {
						clearDraw();
					}
				}
				// } else {
				// 	alert("请先选择解译范围");
				// }
			}
		}
	});
};
// todo 切换面积方式
const currentGeo: Ref<string | undefined> = ref();
// 已绘制的要素
let currentFeature: any;
const changeAreaType = (val: number) => {
	console.log(currentArea.value);

	switch (val) {
		case 3:
			console.log("全部范围");
			mapTool.locationByWkt("ai-interpretation", currentArea.value);
			currentGeo.value = currentArea.value;
			clearDraw();
			mapTool.clearVectorLayer("ai-interpretation");
			break;
		case 6:
			currentGeo.value = "";
			console.log("绘制范围");
			mapTool.clearVectorLayer("ai-interpretation");
			mapTool.addDrawInteraction("ai-interpretation", "Polygon", [
				{
					eventType: "drawstart",
					event: function () {
						if (currentFeature) {
							mapTool.vectorLayerList["ai-interpretation"]
								?.getSource()
								?.removeFeature(currentFeature);
						}
					},
				},
				{
					eventType: "drawend",
					event: function (evt: any) {
						currentFeature = evt.feature;
						currentGeo.value = mapTool.geometryToWkt(evt.feature.getGeometry());
					},
				},
			]);
			break;
		case 9:
			// todo 上传范围接入
			// alert("暂不支持，敬请期待");
			// aiTaskFormData.region = 3;
			clearDraw();
			break;
		default:
			break;
	}
};
const fileLoading = ref(false);
const uploadFile = ref([]);
const beforeFileUpload = async (file: File) => {
	let formData = new FormData();
	formData.append("file", file);
	fileLoading.value = true;
	const res = await shpGeo(formData);
	if (res.code === 200 && res.data.theGeom) {
		mapTool.clearVectorLayer("ai-interpretation");
		mapTool.locationByWkt("ai-interpretation", res.data.theGeom);
		mapTool.loadFeatureByWkt("ai-interpretation", res.data.theGeom, "", false, [
			"rgb(255,0,0)",
			"rgba(255, 0, 0, 0.5)",
		]);
		currentGeo.value = res.data.theGeom;
		fileLoading.value = false;
		return true;
	} else {
		ElMessage({
			message: "解析文件失败",
			type: "error",
		});
		fileLoading.value = false;
		return false;
	}
};
const onRemoveFile = () => {
	mapTool.clearVectorLayer("ai-interpretation");
	mapTool.locationByWkt("ai-interpretation", currentArea.value);
	currentGeo.value = "";
};
// 地图业务,清除画笔交互
const clearDraw = () => {
	mapTool.vectorLayerList["ai-interpretation"]?.getSource()?.removeFeature(currentFeature);
	mapTool.removeDrawInteraction("ai-interpretation");
};
</script>

<style lang="scss" scoped>
/* 解译任务创建弹窗 */
.ai-popup {
	@apply fixed z-20;
	width: 348px;
	right: 20px;
	top: 76px;
	background: rgba(3, 18, 34, 0.9);
	border-radius: 4px;
}
.form-container {
	--el-text-color-regular: #fff;
	@apply px-3 py-6;
}
.type-group {
	@apply grid grid-cols-3;
	.el-checkbox {
		@apply w-1/3;
	}
}
.bottom-btn-group {
	@apply flex justify-between;
	> * {
		@apply w-1/2;
	}
}
.noneUpload {
	:deep().el-upload.is-drag {
		display: none !important;
	}
}
</style>
